// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.entity.NavSellOrderDeclare;
import com.fowo.api.entity.Product;
import com.fowo.api.entity.ProductSub;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.model.nav.sell.order.CustomNavSellOrderDeclareToProductActionVo;
import com.fowo.api.model.product.*;
import com.fowo.api.service.AttributeService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.user.model.JwtUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品 服务实现类
 */
@Service
@Slf4j
@DS("ds24")
public class ProductServiceImpl extends ProductBaseServiceImpl {

    @Resource
    private ProductSubServiceImpl productSubService;
    @Resource
    protected AttributeService attributeService;
    /**
     * 分页查询产品
     * @param search 查询条件
     * @return 产品分页查询结果
     */
    @Override
    public Page<ProductItemVo> pageSearch(ProductSearchParamPo search) {
//        Page<ProductItemVo> page = new Page<>();
//        if (
//                Objects.nonNull(search.getWfStatus()) &&
//                        StringUtils.hasText(search.getFormName())
//        ) {
//            List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
//                    search.getWfStatus(),
//                    search.getFormName()
//            );
//            if (CollectionUtils.isEmpty(workFlowList)) {
//                return page;
//            }
//            List<Long> ids = workFlowList
//                    .stream()
//                    .map(WorkFlow::getRecordId)
//                    .collect(Collectors.toList());
//            if (CollectionUtils.isEmpty(ids)) {
//                return page;
//            }
//            search.setSelectedIds(ids);
//        }
        search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
        Page page = search.toPage();
        Long aLong = this.baseMapper.productCount(search);
        page.setTotal(aLong);
        page.setSearchCount(false);
        page = this.baseMapper.pageSearch(page, search);
//        List<Long> recordIds = page
//                .getRecords()
//                .stream()
//                .map(ProductItemVo::getId)
//                .collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(recordIds)) {
//            return page;
//        }
//        List<WorkFlow> workFlows = workFlowService.queryWfList(
//                recordIds,
//                Collections.singletonList(search.getFormName())
//        );
//        if (CollectionUtils.isEmpty(workFlows)) {
//            return page;
//        }
//        Map<Long, Integer> flowMap = workFlows
//                .stream()
//                .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
//        page
//                .getRecords()
//                .stream()
//                .forEach(item -> {
//                    if (!flowMap.containsKey(item.getId())) {
//                        return;
//                    }
//                    item.setWfStatus(flowMap.get(item.getId()));
//                });
        return page;
    }

    /**
            * 按SKU//全部分页
   */
    @Override
    public Page<ProductItemVo> productPage(ProductSearchParamPo search) {
        Page<ProductItemVo> productPage = new Page<>();
//        if (
//                Objects.nonNull(search.getWfStatus()) &&
//                        StringUtils.hasText(search.getFormName())
//        ) {
//            List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
//                    search.getWfStatus(),
//                    search.getFormName()
//            );
//            if (CollectionUtils.isEmpty(workFlowList)) {
//                return productPage;
//            }
//            List<Long> ids = workFlowList
//                    .stream()
//                    .map(WorkFlow::getRecordId)
//                    .collect(Collectors.toList());
//            if (CollectionUtils.isEmpty(ids)) {
//                return productPage;
//            }
//            search.setSelectedIds(ids);
//        }
        search.initSort("t.id desc", "t.", SORT_FIELD_MAP);

        Page page = search.toPage();
        Long aLong = this.baseMapper.productCount(search);
        page.setTotal(aLong);
        page.setSearchCount(false);

        productPage = this.baseMapper.productPage(page, search);
//        List<Long> recordIds = productPage
//                .getRecords()
//                .stream()
//                .map(ProductItemVo::getId)
//                .collect(Collectors.toList());
//        if (CollectionUtils.isEmpty(recordIds)) {
//            return productPage;
//        }
//        List<WorkFlow> workFlows = workFlowService.queryWfList(
//                recordIds,
//                Collections.singletonList(search.getFormName())
//        );
//        if (CollectionUtils.isEmpty(workFlows)) {
//            return productPage;
//        }
//        Map<Long, Integer> flowMap = workFlows
//                .stream()
//                .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
//        productPage
//                .getRecords()
//                .stream()
//                .forEach(item -> {
//                    if (!flowMap.containsKey(item.getId())) {
//                        return;
//                    }
//                    item.setWfStatus(flowMap.get(item.getId()));
//                });

        return productPage;
    }

    /**
     * 创建产品
     *
     * @param model 产品
     * @return 新数据的主键
     */
    @DataActivity(action = SysDataActivityAction.Add)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(ProductVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        Product entity = new Product();
        BeanUtils.copyProperties(model, entity);
        entity.setCreateTime(new Date());
        entity.setLastUpdateTime(new Date());
        if (StrUtil.equalsIgnoreCase(entity.getType(), "CP06")){
            Product one = this.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, entity.getSpu()).in(Product::getType, entity.getType()),false);
            Assert.isNull(one, "spu已存在！");
        }else{
            Product one = this.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, entity.getSku()).eq(Product::getType,entity.getType()),false);
            Assert.isNull(one, "sku已存在！");
        }

        if (currentUser != null) {
            entity.setCreateUser(currentUser.getUserId());
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (this.save(entity)) {
            model.setId(entity.getId());
            updateAllChilds(model);
            return entity.getId();
        }
        throw new Exception("产品保存失败");
    }


    /**
     * 删除产品
     *
     * @param id 产品的主键
     * @return 删除是否成功
     */
    @DataActivity(action = SysDataActivityAction.Del)
    @Override
    public boolean delete(Long id) throws Exception {
        List<ProductSub> subList = productSubService.list(Wrappers.lambdaQuery(ProductSub.class).eq(ProductSub::getSubId, id));
        if (CollUtil.isNotEmpty(subList)) {
            List<Long> idList = subList.stream().map(s -> s.getProductId()).collect(Collectors.toList());
            List<Product> list = this.list(Wrappers.lambdaQuery(Product.class).in(Product::getId, idList).eq(Product::getDelFlag, 0));
            if (CollUtil.isNotEmpty(list)) {
                throw new Exception("产品绑定其他产品，不允许删除");
            }
        }
        return this.removeById(id);
    }

    /**
     * 批量删除产品
     *
     * @param ids 产品的主键列表
     * @return 删除是否成功
     */
    @Override
    public boolean batchDelete(List<Long> ids) throws Exception {
        for (Long id : ids) {
            List<ProductSub> subList = productSubService.list(Wrappers.lambdaQuery(ProductSub.class).eq(ProductSub::getSubId, id));
            if (CollUtil.isNotEmpty(subList)) {
                List<Long> idList = subList.stream().map(s -> s.getProductId()).collect(Collectors.toList());
                List<Product> list = this.list(Wrappers.lambdaQuery(Product.class).in(Product::getId, idList).eq(Product::getDelFlag, 0));
                if (CollUtil.isNotEmpty(list)) {
                    throw new Exception("产品绑定其他产品，不允许删除");
                }
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据sku获取仓位
     */
    @Override
    public List<ProductGetStorageBinResult> getStorageBin(
            ProductGetStorageBinParam param
    ) {
        List<ProductGetStorageBinResult> storageBin = this.baseMapper.getStorageBin(param);
        for (ProductGetStorageBinResult item : storageBin) {
            item.setStorage_bin(item.getStoragebin());
        }
        return storageBin;
    }

    /**
     * 根据sku获取详情
     *
     * @param sku
     * @return
     */
    public Product getProductBySku(String sku) {
        final List<Product> list = this.list(Wrappers.lambdaQuery(Product.class).eq(Product::getSku, sku).orderByDesc(Product::getId));
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        return CollUtil.getFirst(list);
    }


    /**
     * 更新报关信息
     */
    @DataActivity(
            action = SysDataActivityAction.Other,
            message = "%s执行了批量修改产品操作"
    )
    @Transactional(rollbackFor = Exception.class)
    public void customBatchUpdateProduct(CustomDeclareToProductActionVo vo) throws Exception {
        Assert.isTrue(ObjUtil.isNotEmpty(vo), "参数为空!");
        try {
            for (Long item : vo.getIdList()) {
                ProductVo entity = vo.getEntity();
                entity.setId(item);
                this.update(entity);
            }
        } catch (Exception ex) {
            log.error("发生异常,异常信息:" + StrUtil.subPre(ExceptionUtil.getRootCauseMessage(ex), 2000));
            throw new RuntimeException("发生异常,信息:" + StrUtil.subPre(ExceptionUtil.getRootCauseMessage(ex), 2000));
        }
    }

}
